<template>
	<div>
		<cl-crud @load="onLoad">
			<template #table-column-status="{scope}">
				<el-tag v-if="scope.row.status == 2">禁用</el-tag>
				<el-tag type="success" v-else-if="scope.row.status == 1">启用</el-tag>
			</template>
			<!-- 一键查询 -->
			<template #slot-click-query>
				<el-button
					type="primary"
					size="mini"
					:disabled="selectRow.length > 0 ? false : true"
					@click="clickSearch"
					>一键查询用户</el-button
				>
			</template>
<!--			 一键推送 -->
<!--			<template #slot-click-push>-->
<!--				<el-button-->
<!--					type="primary"-->
<!--					size="mini"-->
<!--					:disabled="selectRow.length > 0 ? false : true"-->
<!--					@click="clickPush"-->
<!--					>一键推送消息</el-button-->
<!--				>-->
<!--			</template>-->
			<!-- 查询该标签用户 -->
			<template #table-column-queryUser="{scope}">
				<el-button
					size="mini"
					:loading="scope.row.startStatus == 1"
					@click="qureyBtn(scope.row)"
				>
					<span v-if="scope.row.startStatus == 0">开始查询</span>
					<span v-if="scope.row.startStatus == 1">查询中</span>
					<span v-if="scope.row.startStatus == 2">查询成功</span>
					<span v-if="scope.row.startStatus == 3">查询失败</span>
				</el-button>
			</template>
		</cl-crud>
		<cl-form ref="cl-form"></cl-form>
		<cl-form ref="cl-form-tag"></cl-form>
	</div>
</template>

<script>
import platform from '@/mixin/platform';
import moment from 'moment';

export default {
	data() {
		return {
			selectRow: []
		};
	},
	mixins: [platform],

	mounted() {},

	methods: {
		onLoad({ ctx, app }) {
			this.crud = app;
			ctx.service(this.$service.msgList.tagList)
				.set('dict', {
					label: {
						add: '添加标签'
					}
				})
				.set('table', {
					columns: [
						{
							label: '全选',
							type: 'selection',
							align: 'center',
							width: 60
						},
						{
							label: '序号',
							type: 'index',
							align: 'center',
							width: 60
						},
						{
							label: '标签',
							prop: 'tagName',
							align: 'center',
							emptyText: '---'
						},
						{
							label: 'key',
							prop: 'tagKey',
							align: 'center',
							emptyText: '---'
						},
						{
							label: '标签定义（规则）',
							prop: 'role',
							align: 'center',
							emptyText: '未绑定'
						},
						{
							label: '查询该标签用户',
							prop: 'queryUser',
							align: 'center'
						},
						{
							label: '最近查询时间',
							prop: 'updateTime',
							align: 'center',
							sortable: 'custom'
						},
						{
							label: '是否启用',
							prop: 'status',
							align: 'center'
						}
					],

					op: {
						layout: ['edit', 'delete']
					},

					on: {
						'selection-change': selection => {
							this.selectRow = selection;
						}
					}
				})
				.set('upsert', {
					props: {
						labelWidth: '150px',
						center: true,
						'custom-class': 'custom-class-dialog-mini'
					},
					items: [
						{
							label: '标签',
							prop: 'tagName',
							span: 15,
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请输入标签'
								}
							},
							rules: {
								required: true,
								message: '请输入标签'
							}
						},
						{
							label: 'key',
							prop: 'tagKey',
							span: 15,
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请输入标签key'
								}
							},
							rules: {
								required: true,
								message: '请输入标签key'
							}
						},
						{
							label: '标签定义（规则）',
							prop: 'role',
							span: 15,
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请输入标签定义',
									type: 'textarea'
								}
							},
							rules: {
								required: true,
								message: '请输入标签定义'
							}
						},
						{
							label: '状态',
							prop: 'status',
							value: 1,
							component: {
								name: 'el-radio-group',
								options: [
									{
										label: '启用',
										value: 1
									},
									{
										label: '禁用',
										value: 2
									}
								]
							}
						}
					]
				})
				.set('layout', [
					[
						'refresh-btn',
						'add-btn',
						'slot-click-query',
						'slot-click-push',
						'query',
						'flex1',
						'search-key'
					],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('refresh', async (params, { render, next }) => {
					let { list } = await next(params);
					list.map(item => {
						item.loading = false;
					});
					render(list);
				})
				.done();

			app.refresh();
		},
		qureyBtn(e) {
			this.$service.msgList.tagList
				.start({
					ids: e.id
				})
				.then(() => {
					this.crud.refresh();

					setTimeout(() => {
						this.crud.refresh();

						setTimeout(() => {
							this.$router.push({
								path: '/msgList/userResult',
								query: {
									tagIds: e.id,
									tagName: e.tagName
								}
							})
						}, 2000);
					}, 10000)
				})
				.catch(err => {
					this.$message.error(err);
				});
		},
		clickSearch() {
			let idsArr = [];
			let tagArr = [];
			this.selectRow.forEach(item => {
				idsArr.push(item.id);
				tagArr.push(item.tagName);
			});

			this.$service.msgList.tagList
					.start({
						ids: idsArr.join(',')
					})
					.then(() => {
						this.crud.refresh();

						setTimeout(() => {
							this.crud.refresh();

							setTimeout(() => {
								this.$router.push({
									path: '/msgList/userResult',
									query: {
										tagIds: idsArr.join(','),
										tagName: tagArr.join(',')
									}
								})
							}, 2000);
						}, 10000)
					})
					.catch(err => {
						this.$message.error(err);
					});
		},
		async clickPush() {
			const that = this;
			const list = await that.$service.msgList.tagList.list();
			let selectTag = [];
			let tagList = [];

			that.selectRow.map(item => {
				selectTag.push(item.tagName);
			});
			list.map(i => {
				tagList.push(i.tagName);
			});
			let app = that.$refs['cl-form'].open({
				props: {
					title: '消息设置',
					labelWidth: '120px',
					center: true,
					'custom-class': 'custom-class-dialog-mini'
				},
				items: [
					{
						label: 'LOGO',
						prop: 'icon',
						span: 24,
						component: {
							name: 'cl-upload'
						}
					},
					{
						label: '标题',
						prop: 'title',
						span: 15,
						component: {
							name: 'el-input',
							attrs: {
								placeholder: '请输入标题'
							}
						},
						rules: {
							required: true,
							message: '请输入标题'
						}
					},
					{
						label: '活动类型',
						prop: 'type',
						span: 8,
						value: 2,
						component: {
							name: 'el-select',
							attrs: {
								placeholder: '请选择'
							},
							props: {
								clearable: true
							},
							options: [
								{
									label: '标签消息',
									value: 2
								},
							],
							on: {
								change(val) {
									if (val === 2) {
										app.hiddenItem('label', false);
									} else {
										app.hiddenItem('label', true);
									}
								}
							}
						},
						rules: {
							required: true,
							message: '任务类型不能为空'
						}
					},
					{
						label: '内容',
						prop: 'content',
						span: 24,
						component: {
							name: 'el-input-content',
							data() {
								return {
									value2: '',
									options: [
										{
											label: '标题',
											value: '{title}'
										},
										{
											label: '在售价',
											value: '{price}'
										},
										{
											label: '优惠券',
											value: '{couponMoney}'
										},
										{
											label: '券后价',
											value: '{endPrice}'
										},
										{
											label: '淘口令',
											value: '{tkl}'
										}
									]
								};
							},
							watch: {
								value(val) {
									this.value2 = val;
								}
							},
							props: {
								value: [String, Number]
							},
							methods: {
								Click(val) {
									this.value2 += val.target.dataset.val;
								},
								input(val) {
									this.$emit('input', val);
								}
							},
							render() {
								return (
									<div>
										<div>
											{this.options.map(item => {
												return (
													<el-tag
														class="cursor-tag"
														onClick={this.Click}
														data-val={item.value}
														type="info">
														{item.label}
													</el-tag>
												);
											})}
										</div>
										<el-input
											rows={8}
											type="textarea"
											onInput={this.input}
											v-model={this.value2}></el-input>
									</div>
								);
							}
						}
					},
					{
						prop: 'tinyint',
						label: '推送时间',
						span: 12,
						value: 1,
						component: {
							name: 'el-select',
							options: [
								{
									label: '立即推送',
									value: 1
								},
								{
									label: '预设时间',
									value: 0
								},
								{
									label: '每日推送',
									value: 2
								}
							]
						},
						rules: [
							{
								validator: (rules, value, callback) => {
									if (value == 0) {
										app.hiddenItem('pushTime', false);
									} else {
										app.hiddenItem('pushTime', true);
									}
									if (value == 2) {
										app.hiddenItem('cron', false);
									} else {
										app.hiddenItem('cron', true);
									}
									callback();
								}
							}
						]
					},
					{
						hidden: false,
						label: '推送标签',
						prop: 'label',
						span: 12,
						value: selectTag,
						component: {
							name: 'slot-select-tag',
							data() {
								return {
									selectLabel: []
								};
							},
							attrs: {
								list: tagList
							},
							props: {
								value: [Array],
								list: [Array]
							},
							mounted() {
								this.selectLabel = this.value;
							},
							methods: {
								change(val) {
									this.$emit('input', val);
								},
								createLabel() {
									that.$refs['cl-form-tag'].open({
										props: {
											title: '创建标签',
											labelWidth: '120px',
											center: true,
											'custom-class': 'custom-class-dialog-mini'
										},
										items: [
											{
												label: '标签名',
												prop: 'tagName',
												span: 15,
												component: {
													name: 'el-input',
													attrs: {
														placeholder: '标签名'
													}
												},
												rules: {
													required: true,
													message: '标签名'
												}
											}
										],
										on: {
											submit: ({ data, close }) => {
												this.list.push(data.tagName);
												close();
											}
										}
									});
								}
							},
							render() {
								return (
									<div>
										<el-select
											v-model={this.selectLabel}
											multiple
											size="small"
											onChange={this.change}
											placeholder="请选择标签">
											{tagList.map(item => {
												return (
													<el-option
														label={item}
														value={item}></el-option>
												);
											})}
										</el-select>
									</div>
								);
							}
						},
						rules: {
							required: true,
							message: '推送标签不能为空'
						}
					},
					{
						prop: 'pushTime',
						label: '预设时间',
						span: 12,
						hidden: true,
						value: moment().format('YYYY-MM-DD HH:mm:ss'),
						component: {
							name: 'el-date-picker',
							props: {
								type: 'datetime',
								'value-format': 'yyyy-MM-dd HH:mm:ss'
							}
						},
						rules: [
							{
								validator: (rules, value, callback) => {
									const h = app.getData('upsert.form.hour') || 0;
									if (
										moment(value)
											.add(h, 'hour')
											.isBefore(moment())
									) {
										callback(new Error('推送时间不能小于当前时间'));
									} else {
										callback();
									}
								}
							}
						]
					},
					{
						prop: 'cron',
						label: '推送时间',
						span: 11,
						hidden: true,
						value: moment().format('HH:mm:ss'),
						component: {
							name: 'el-time-picker',
							props: {
								'value-format': 'HH:mm:ss'
							}
						},
						rules: {
							required: true,
							message: '推送时间'
						}
					},
					{
						label: '备注',
						prop: 'remark',
						span: 23,
						component: {
							name: 'el-input',
							attrs: {
								placeholder: '请输入备注'
							}
						}
					},
					{
						label: '状态',
						prop: 'status',
						value: 1,
						component: {
							name: 'el-radio-group',
							options: [
								{
									label: '启用',
									value: 1
								},
								{
									label: '禁用',
									value: 0
								}
							]
						}
					}
				],
				on: {
					submit: ({ data, close, done }) => {
						let params = data;
						let idsArr = [];
						// 根据标签名去查询id
						list.forEach(listItem => {
							params.label.forEach(labelItem => {
								if (listItem.tagName === labelItem) {
									idsArr.push(listItem.id);
								}
							})
						});
						params.ids = idsArr.join(',');
						params.label = params.label.join(',');
						if (data.type !== 2) {
							data.label = undefined;
						}
						this.$service.msgList.tagList
								.pushMessage({
									...data,
								})
								.then(() => {
									this.$message.success('创建成功');
									close();
								})
								.catch(err => {
									this.$message.error(err);
									done();
								});
					}
				}
			});
		}
	}
};
</script>
<style lang="scss" scoped></style>
